<template>
  <div>
    <base-table ref="table" :search-params="searchParams" :columns="columnsAction" :async-fc="page">
      <template #tableHeader>
        <t-button @click="insert">{{ t('components.commonTable.insert') }}</t-button>
      </template>
    </base-table>
    <t-dialog v-model:visible="modalOpen" width="45%" @confirm="onModalSubmit">
      <t-form ref="submitFormRef" style="width: 100%" :rules="rules" :data="submitForm" label-align="top">
        <t-row style="width: 100%" :gutter="[16, 16]">
          <t-col :span="6">
            <t-form-item :label="t('pages.userList.username')" name="username">
              <t-input v-model="submitForm.username" :placeholder="t('pages.userList.usernamePlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col v-if="!submitForm.id" :span="6">
            <t-form-item :label="t('pages.userList.password')" name="password">
              <t-input
                v-model="submitForm.password"
                type="password"
                :placeholder="t('pages.userList.passwordPlaceholder')"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userList.sex')" name="sex">
              <t-select v-model="submitForm.sex" :placeholder="t('pages.userList.sexPlaceholder')">
                <t-option :value="0" label="男" />
                <t-option :value="1" label="女" />
                <t-option :value="2" label="未知" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userList.nickname')" name="nickname">
              <t-input v-model="submitForm.nickname" :placeholder="t('pages.userList.nicknamePlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userList.phone')" name="phone">
              <t-input v-model="submitForm.phone" :placeholder="t('pages.userList.phonePlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userList.email')" name="email">
              <t-input v-model="submitForm.email" :placeholder="t('pages.userList.emailPlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userList.role')" name="role">
              <t-select
                v-model="submitForm.roles"
                :options="roleList"
                value-type="object"
                multiple
                :placeholder="t('pages.userList.rolePlaceholder')"
              >
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <common-upload
              v-model:value="submitForm.avatar"
              :value-type="'data'"
              :limit="1"
              :tip="t('pages.userList.avatarPlaceholder')"
            ></common-upload>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userList.status')" name="status">
              <t-select v-model="submitForm.status" :placeholder="t('pages.userList.statusPlaceholder')">
                <t-option :value="1" label="开启" />
                <t-option :value="0" label="关闭" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item :label="t('pages.userList.remark')" name="remark">
              <t-textarea v-model="submitForm.remark" :placeholder="t('pages.userList.remarkPlaceholder')" />
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </t-dialog>
  </div>
</template>
<script setup lang="ts">
import { DialogPlugin, FormInstanceFunctions, Link, MessagePlugin, Space } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';

import { deleteById, getRoleList, insertApi, page, resetPasswordApi, updateApi } from '@/api/sys_user';
import baseTable from '@/components/base-table/index.vue';
import commonUpload from '@/components/common-upload/index.vue';
import { t } from '@/locales';

import { getColumns, getRules, getSearchParams } from './constants';

const submitForm = ref<any>({});
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<_TableInstanceFunctions>(null);
const roleList = ref([]);

const searchParams = computed(() => getSearchParams());
const rules = computed(() => getRules());
const columns = computed(() => getColumns());

const columnsAction = computed(() =>
  columns.value.concat([
    {
      align: 'center',
      fixed: 'right',
      colKey: 'op',
      title: t('components.commonTable.operation'),
      cell: (h, { row }) =>
        h(
          Space,
          {
            split: 'line',
            size: 'small',
            style: 'min-width: 160px; justify-content: center;',
          },
          () => [
            h(
              Link,
              {
                theme: 'primary',
                underline: false,
                onClick: () => {
                  submitForm.value = row;
                  modalOpen.value = true;
                },
              },
              () => t('components.commonTable.edit'),
            ),
            h(
              Link,
              {
                theme: 'danger',
                underline: false,
                onClick: () => {
                  const confirmDialog = DialogPlugin.confirm({
                    header: t('components.commonTable.tips'),
                    body: t('components.commonTable.deleteConfirm'),
                    confirmBtn: {
                      content: t('components.commonTable.submit'),
                      theme: 'primary',
                      loading: false,
                    },
                    cancelBtn: {
                      content: t('components.commonTable.cancel'),
                      theme: 'default',
                      loading: false,
                    },
                    theme: 'warning',
                    onConfirm: async () => {
                      confirmDialog.update({
                        confirmBtn: { content: t('components.commonTable.submitting'), loading: true },
                      });
                      await deleteById(row.id);
                      MessagePlugin.success(t('components.commonTable.deleteSuccess'));
                      table.value.onSearch();
                      confirmDialog.update({
                        confirmBtn: { content: t('components.commonTable.submit'), loading: false },
                      });
                      confirmDialog.hide();
                    },
                  });
                },
              },
              () => t('components.commonTable.delete'),
            ),
            h(
              Link,
              {
                theme: 'warning',
                underline: false,
                onClick: () => {
                  const confirmDialog = DialogPlugin.confirm({
                    header: t('components.commonTable.tips'),
                    body: '确认要重置该用户的密码吗？',
                    confirmBtn: {
                      content: t('components.commonTable.submit'),
                      theme: 'primary',
                      loading: false,
                    },
                    cancelBtn: {
                      content: t('components.commonTable.cancel'),
                      theme: 'default',
                      loading: false,
                    },
                    theme: 'warning',
                    onConfirm: async () => {
                      confirmDialog.update({
                        confirmBtn: { content: t('components.commonTable.submitting'), loading: true },
                      });
                      await resetPasswordApi(row.id);
                      MessagePlugin.success('密码重置成功');
                      confirmDialog.update({
                        confirmBtn: { content: t('components.commonTable.submit'), loading: false },
                      });
                      confirmDialog.hide();
                    },
                  });
                },
              },
              () => '重置密码',
            ),
          ],
        ),
    },
  ]),
);

const insert = () => {
  modalOpen.value = true;
  submitForm.value = {
    sex: 2,
  };
};

/**
 * 提交表单
 */
const onModalSubmit = async () => {
  const valid = await submitFormRef.value.validate();
  if (valid === true) {
    if (submitForm.value.id) {
      await updateApi(submitForm.value);
    } else {
      await insertApi(submitForm.value);
    }
    MessagePlugin.success('操作成功！');
    modalOpen.value = false;
    table.value.onSearch();
  }
};

onMounted(async () => {
  roleList.value = await getRoleList();
});
</script>

<style lang="less" scoped>
:deep(.t-button) {
  min-width: 88px;

  .t-icon {
    font-size: 16px;
  }
}

:deep(.t-dialog) {
  .t-dialog__body {
    max-height: calc(90vh - 200px);
    overflow-y: auto;
  }

  .t-form {
    .t-form__item {
      padding: 0 0 24px 0;
      margin-bottom: 0;

      &:last-child {
        padding-bottom: 0;
      }
    }

    .t-radio-group {
      display: flex;
      gap: 32px;
    }
  }
}

:deep(.t-tag) {
  width: 68px;
  justify-content: center;

  &.t-tag--primary {
    background: rgba(0, 82, 217, 0.1);
    color: #0052d9;
  }

  &.t-tag--success {
    background: rgba(0, 168, 112, 0.1);
    color: #00a870;
  }
}

:deep(.t-table) {
  .t-avatar {
    width: 40px;
    height: 40px;
    font-size: 16px;
    background: #e3e6eb;
  }
}
</style>
